package com.gadgets.framework.start;

import com.gadgets.framework.common.util.SpringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collections;

/**
 * @author UncleXiu
 * @version V1.0.0
 * @data 2020-09-13
 * 
 */
@Component
public class StartInitLoader implements ApplicationListener<ContextRefreshedEvent> {

    private static final Logger logger = LoggerFactory.getLogger("startup");

    /**
     * Handle an application event.
     *
     * @param event the event to respond to
     */
    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        logger.info("Spring启动完成，开始Gadgets初始化加载器执行");
        ApplicationContext context = event.getApplicationContext();
        SpringUtils.registry(context);
        String[] initProcesses = context.getBeanNamesForType(AbstractInitLoaderProcess.class);
        ArrayList<AbstractInitLoaderProcess> processes = new ArrayList<>();
        // 获取启动加载处理器
        if(initProcesses.length>0) {
            for (String initProcess : initProcesses) {
                AbstractInitLoaderProcess startInitLoader = context.getBean(initProcess, AbstractInitLoaderProcess.class);
                processes.add(startInitLoader);
            }
            // 处理器排序
            Collections.sort(processes);
            for (AbstractInitLoaderProcess process : processes) {
                process.initLoad(context);
            }
        }
        logger.info("Spring启动完成，开始Gadgets初始化加载器执行结束");
    }

}
